/**
 * @(#)Main.java 2011-8-24 Copyright 2011 it.kedacom.com, Inc. All rights
 *               reserved.
 */

package com.kedacom.xmpp.demo.oneserver.chat;

import java.util.Collection;

import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.ChatState;
import org.jivesoftware.smackx.muc.InvitationListener;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.packet.ChatStateExtension;

/**
 * (用一句话描述类的主要功能)
 * @author xiaojinghai
 * @date 2011-8-24
 */

public class ChatInOneServer {

	/**
	 * (用一句话描述方法的主要功能)
	 * @param args
	 * @throws XMPPException
	 * @throws InterruptedException
	 */

	public static void main(String[] args) throws XMPPException, InterruptedException {
		// Connection.DEBUG_ENABLED = true;
		String SERVER = "kedacom.com", RESOURCE = "java", USER1 = "hexiaogang", PASS1 = "888", USER2 = "kongchun", PASS2 = "888";
		Connection conn1 = null, conn2 = null;

		// user1 login
		conn1 = new XMPPConnection(SERVER);
		conn1.connect();
		conn1.login(USER1, PASS1, RESOURCE);
		System.out.println("user1已登录!");
		// user2 login
		conn2 = new XMPPConnection(SERVER);
		conn2.connect();
		conn2.login(USER2, PASS2, RESOURCE);
		System.out.println("user2已登录!");
		// 设置登录状态
		Presence p = new Presence(Presence.Type.available);
		p.setStatus("可以隐身吗？");
		conn1.sendPacket(p);
		// 设置登录状态
		Presence p2 = new Presence(Presence.Type.available);
		p2.setStatus("发呆中。。。");
		conn2.sendPacket(p2);

		// 获取我的好友列表
		// Collection<RosterEntry> rosters = conn1.getRoster().getEntries();
		Collection<RosterEntry> rosters = conn1.getRoster().getEntries();
		System.out.println("=======================我的好友列表：=======================");
		for (RosterEntry rosterEntry : rosters) {
			System.out.print("name: " + rosterEntry.getName() + ",jid: " + rosterEntry.getUser());
			System.out.println("");
		}
		System.out.println("=======================我的好友列表：=======================");

		// 被动接收信息
		conn2.getChatManager().addChatListener(new ChatManagerListener() {

			public void chatCreated(org.jivesoftware.smack.Chat chat, boolean createdLocally) {
				chat.addMessageListener(new MessageListener() {

					public void processMessage(org.jivesoftware.smack.Chat chat, Message message) {
						String messageBody = message.getBody();
						PacketExtension pe;

						pe = message.getExtension("composing", "http://jabber.org/protocol/chatstates");
						if (pe != null) {
							System.out.println("对方正在输入......");
							return;
						}

						pe = message.getExtension("active", "http://jabber.org/protocol/chatstates");
						if (pe != null) {
							System.out.println("接收到信息：" + messageBody);
							return;
						}

						pe = message.getExtension("paused", "http://jabber.org/protocol/chatstates");
						if (pe != null) {
							System.out.println("对方已暂停输入");
							return;
						}

						pe = message.getExtension("inactive", "http://jabber.org/protocol/chatstates");
						if (pe != null) {
							System.out.println("对方聊天窗口失去焦点");
							return;
						}

						pe = message.getExtension("gone", "http://jabber.org/protocol/chatstates");
						if (pe != null) {
							System.out.println("对方聊天窗口被关闭");
							return;
						}

						System.out.println("接收到信息：" + messageBody);

					}
				});
			}

		});

		ChatManager chatmanager = conn1.getChatManager();

		org.jivesoftware.smack.Chat newChat = chatmanager.createChat("user2@xmpptesta.com", new MessageListener() {

			public void processMessage(org.jivesoftware.smack.Chat chat, Message message) {
				System.out.println("user1接收到信息: " + message.getBody());

			}
		});
		// 主动发信息
		// 发送给test1初始文本信息,附带正在输入的状态
		Message mess = new Message();
		mess.addExtension(new ChatStateExtension(ChatState.composing));
		newChat.sendMessage(mess);
		Thread.currentThread().sleep(1000);

		// 发送给test1初始文本信息,附带输入状态
		mess = new Message();
		mess.addExtension(new ChatStateExtension(ChatState.active));
		mess.setBody("你好!");
		newChat.sendMessage(mess);
		Thread.currentThread().sleep(1000);

		// 发送给test1初始文本信息,附带暂停输入的状态
		mess = new Message();
		mess.addExtension(new ChatStateExtension(ChatState.paused));
		newChat.sendMessage(mess);

		// 邀请多人聊天
		MultiUserChat.addInvitationListener(conn1, new InvitationListener() {

			public void invitationReceived(Connection conn, String room, String inviter, String reason,
					String password, Message message) {
				MultiUserChat multiUserChat = new MultiUserChat(conn, room);
				System.out.println("收到来自 " + inviter + " 的聊天室邀请。邀请附带内容：" + reason);
				try {
					multiUserChat.join("user1", password);
				} catch (XMPPException e) {
					System.out.println("加入聊天室失败");
					e.printStackTrace();
				}
				System.out.println("成功加入聊天室");
				multiUserChat.addMessageListener(new PacketListener() {

					public void processPacket(Packet packet) {
						Message message = (Message) packet;
						// 接收来自聊天室的聊天信息
						System.out.println(message.getFrom() + ":" + message.getBody());
					}
				});
				// 发送信息到聊天室
				try {
					multiUserChat.sendMessage("新手到来，大家关照！");
				} catch (XMPPException e) {
					// TODO 尚未处理异常
					e.printStackTrace();
				}
			}

		});

		MultiUserChat.addInvitationListener(conn2, new InvitationListener() {

			public void invitationReceived(Connection conn, String room, String inviter, String reason,
					String password, Message message) {
				MultiUserChat multiUserChat = new MultiUserChat(conn, room);
				System.out.println("收到来自 " + inviter + " 的聊天室邀请。邀请附带内容：" + reason);
				try {
					multiUserChat.join("user2", password);
				} catch (XMPPException e) {
					System.out.println("加入聊天室失败");
					e.printStackTrace();
				}
				System.out.println("成功加入聊天室");
				multiUserChat.addMessageListener(new PacketListener() {

					public void processPacket(Packet packet) {
						Message message = (Message) packet;
						// 接收来自聊天室的聊天信息
						System.out.println(message.getFrom() + ":" + message.getBody());
					}
				});

				// 发送信息到聊天室
				try {
					multiUserChat.sendMessage("新手到来，大家关照！");
				} catch (XMPPException e) {
					// TODO 尚未处理异常
					e.printStackTrace();
				}

			}

		});

		Thread.currentThread().suspend();
	}

	public static void loginToGTalk() throws XMPPException {
		XMPPConnection conn = new XMPPConnection(new ConnectionConfiguration("talk.google.com", 5222, "gmail.com"));
		conn.connect();
		// 输入gtalk的账号密码
		conn.login("88888888", "8888888888");
		Collection<RosterEntry> rosters = conn.getRoster().getEntries();
		// 获取gtalk上的好友列表
		System.out.println("我的好友列表：=======================");
		for (RosterEntry rosterEntry : rosters) {
			System.out.print("name: " + rosterEntry.getName() + ",jid: " + rosterEntry.getUser());
			System.out.println("");
		}
		System.out.println("我的好友列表：=======================");

		conn.disconnect();
	}
}
